//
// Created by 崔世强 on 2018/4/25.
// Copyright (c) 2018 Facebook. All rights reserved.
//

import Foundation
import SnapKit
import Kingfisher
import WCDBSwift
import Toast_Swift
import SwiftyJSON

class AddGroupMemberController: ChatBaseController {
    lazy var tableView: UITableView = {
        var table = UITableView()
        table.delegate = self
        table.dataSource = self
        table.separatorStyle = .singleLine
        table.isEditing = true
        table.allowsMultipleSelectionDuringEditing = true
        table.sectionIndexColor = .gray
        table.tableFooterView = UIView(frame: CGRect.zero)
        table.estimatedRowHeight = 50
        return table
    }()
    
    private let text = "确定"
    
    lazy var doneButtonItem: UIBarButtonItem = {
        let barItem = UIBarButtonItem(title: text, style: .plain, target: self, action: #selector(done))
        barItem.tintColor = kBtnGreen
        barItem.isEnabled = false
        return barItem
    }()
    
    var groupId: Int!
    var contactList:[ChatContact] = [ChatContact]()
    var sectionsArray: [[ChatContact]] = [[ChatContact]]()
    var indexArray: [String] = [String]()
    var selected = Set<Int>()
    var groupMembers: Set<Int> = Set<Int>()
    
    var collation = UILocalizedIndexedCollation.current()
    let service = GroupService()
    let msgService = ChatService()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "联系人"
        self.navigationItem.rightBarButtonItem = doneButtonItem
        
        self.view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalTo(self.view)
        }
        
        let db = SQLiteHelper.getDb()
        do {
            try db.run(transaction: { [unowned self]_ in
                let contacts = try ContactDao.getAllContact()
                for contact in contacts {
                    self.contactList.append(ChatContact(userId: contact.userId, displayName: (contact.remarkName ?? contact.name),avatar:contact.avatar))
                }
                self.groupMembers = try self.service.getGroupMemberIdSet(self.groupId, limit: 100000)
                print(groupMembers)
                setSection()
            })
        } catch {
            print(error)
        }
    }
    
    func setSection(){
        //        self.collation = UILocalizedIndexedCollation.current()
        let sectionTitlesCount = self.collation.sectionTitles.count
        print(sectionTitlesCount)
        //临时数据，存放section对应的userObjs数组数据
        var newSectionsArray = [[ChatContact]]()
        
        //设置sections数组初始化：元素包含userObjs数据的空数据
        for _ in 0 ..< sectionTitlesCount {
            let array = [ChatContact]()
            newSectionsArray.append(array)
        }
        
        //将用户数据进行分类，存储到对应的sesion数组中
        
        for contact in contactList {
            //根据timezone的localename，获得对应的的section number
            let sectionNumber = self.collation.section(for: contact, collationStringSelector: #selector(getter: ChatContact.displayName))
            let headerString = self.collation.sectionTitles[sectionNumber]
            if !indexArray.contains(headerString) {
                indexArray.append(headerString)
            }
            
            //获得section的数组
            var sectionBeans = newSectionsArray[sectionNumber]
            
            //添加内容到section中
            sectionBeans.append(contact)
            
            // swift 数组是值类型，要重新赋值
            newSectionsArray[sectionNumber] = sectionBeans
        }
        //        print(self.indexArray)
        
        
        //排序，对每个已经分类的数组中的数据进行排序，如果仅仅只是分类的话可以不用这步
        for i in 0 ..< sectionTitlesCount {
            let beansArrayForSection = newSectionsArray[i]
            //获得排序结果
            let sortedBeansArrayForSection = collation.sortedArray(from: beansArrayForSection, collationStringSelector:  #selector(getter: ChatContact.displayName))
            //替换原来数组
            newSectionsArray[i] = sortedBeansArrayForSection as! [ChatContact]
            
        }
        
        sectionsArray = newSectionsArray
    }
    
    fileprivate func onAddMemberSuccess() {
        DispatchQueue.main.async {
            self.view.hideModalToastActivity()
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    fileprivate func onAddMemberFailure(_ msg: String) {
        DispatchQueue.main.async {
            self.view.hideModalToastActivity()
            self.view.makeToast(msg, position: .center)
        }
    }
    
    @objc func done() {
        self.view.makeModalToastActivity(.center)
        let userIds = Array(self.selected)
        IM.request(.addGroupMembers(groupId: groupId, manageId: AppStatusManager.instance.userLoginStatus.1 ?? 0, userIds: userIds), success: { [unowned self] (json) in
            if reqSuccess(json["code"].stringValue) {
                do {
                    try self.service.add(self.groupId, members: userIds)
                } catch {
                    print(error)
                }
                self.onAddMemberSuccess()
            } else {
                let msg = json["msg"].stringValue
                self.onAddMemberFailure(msg)
            }
            }, error: { (code) in
                print("状态异常：\(code)")
                self.onAddMemberFailure("服务异常，请稍后再试")
        }) { (error) in
            print(error)
            self.onAddMemberFailure("服务或网络异常")
        }
    }
}

extension AddGroupMemberController: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if sectionsArray.count == 0 {
            return 0
        }
        let beanInSection = sectionsArray[section]
        return beanInSection.count
    }
    
    
    //生成表视图单元格
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let singleLine = "singleLine"
        var cell = tableView.dequeueReusableCell(withIdentifier: singleLine) as? SelectViewCell
        if cell == nil {
            cell = SelectViewCell(style: .default, reuseIdentifier: singleLine)
            cell?.multipleSelectionBackgroundView = UIView()
            
        }
        //        let contact = contactList[indexPath.row]
        let userNameInSection = sectionsArray[indexPath.section]
        let contact = userNameInSection[indexPath.row]
        if groupMembers.contains(contact.userId) {
            cell?.tintColor = .lightGray
            tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
        } else {
            cell?.tintColor = kBtnGreen
        }
        cell!.nameLabel.text = contact.displayName
        cell!.avatar.kf.setImage(with: KF.ImageResource(downloadURL: Common.avatarUrl(contact.avatar ?? "") ?? URL(string: "localhost")!), for: .normal, placeholder: #imageLiteral(resourceName:"defaultAvatar"),options: [.processor(CryptorProcessor())])
        return cell!
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.collation.sectionTitles.count
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if sectionsArray.count == 0 {
            return nil
        }
        let beansInSection = sectionsArray[section]
        if (beansInSection as AnyObject).count <= 0 {
            return nil
        }
        let headerString = collation.sectionTitles[section]
        return headerString
    }
    //设置索引标题
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return collation.sectionTitles
        //        return self.indexArray
    }
    
    //关联搜索
    func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        return collation.section(forSectionIndexTitle: index)
    }
}

extension AddGroupMemberController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //        let contact = contactList[indexPath.row]
        let userNameInSection = sectionsArray[indexPath.section]
        let contact = userNameInSection[indexPath.row]
        self.selected.insert(contact.userId)
        self.doneButtonItem.title = "\(text)(\(self.selected.count))"
        self.doneButtonItem.isEnabled = true
    }
    
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath){
        //        let contact = contactList[indexPath.row]
        let userNameInSection = sectionsArray[indexPath.section]
        let contact = userNameInSection[indexPath.row]
        self.selected.remove(contact.userId)
        let numberText = self.selected.isEmpty ? "" : "(\(self.selected.count))"
        self.doneButtonItem.title = "\(text)\(numberText)"
        self.doneButtonItem.isEnabled = !self.selected.isEmpty
    }
    
    //    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    //        let contact = contactList[indexPath.row]
    //        let cell = tableView.cellForRow(at: indexPath)
    //
    //    }
    
    //将选中某行
    func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
        let userNameInSection = sectionsArray[indexPath.section]
        let contact = userNameInSection[indexPath.row]
        if groupMembers.contains(contact.userId) {
            return nil
        }
        return indexPath
    }
    
    //将选中某行
    func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath? {
        let userNameInSection = sectionsArray[indexPath.section]
        let contact = userNameInSection[indexPath.row]
        if groupMembers.contains(contact.userId) {
            return nil
        }
        return indexPath
    }
}
